const fs = require('fs');
const sourceMap = require('source-map');

function extractGeneratedPosition(errorStack) {
    const pattern = /:\d+:\d+/;
    const match = errorStack.match(pattern);

    if (!match) return null;

    const parts = match[0].slice(1).split(':');
    return {
        line: parseInt(parts[0]),
        column: parseInt(parts[1]),
    };
}

async function parseError({ line, column }) {
    const rawSourceMap = JSON.parse(fs.readFileSync('./dist/js/prod.main.8ca1f1942537835b0b8c.js.map'));
    const consumer = await new sourceMap.SourceMapConsumer(rawSourceMap);

    const generatedPosition = {
        line,
        column,
    };

    const originalPosition = consumer.originalPositionFor(generatedPosition);

    console.log('源码位置:', {
        file: originalPosition.source,
        line: originalPosition.line,
        column: originalPosition.column,
        name: originalPosition.name,
    });

    const content = consumer.sourceContentFor(originalPosition.source);
    const lines = content.split('\n');
    console.log('相关代码:', lines.slice(originalPosition.line - 3, originalPosition.line + 2).join('\n'));
}

parseError(
    extractGeneratedPosition(`TypeError: Cannot read properties of null (reading 'concat')
    at http://localhost:3333/js/prod.main.8ca1f1942537835b0b8c.js:2:152492
    at Array.map (<anonymous>)
    at http://localhost:3333/js/prod.main.8ca1f1942537835b0b8c.js:2:152466
    at Ji (http://localhost:3333/js/prod.main.8ca1f1942537835b0b8c.js:2:64132)
    at Ll (http://localhost:3333/js/prod.main.8ca1f1942537835b0b8c.js:2:72074)
    at Ea (http://localhost:3333/js/prod.main.8ca1f1942537835b0b8c.js:2:112426)
    at Tu (http://localhost:3333/js/prod.main.8ca1f1942537835b0b8c.js:2:102938)
    at xu (http://localhost:3333/js/prod.main.8ca1f1942537835b0b8c.js:2:102863)
    at hu (http://localhost:3333/js/prod.main.8ca1f1942537835b0b8c.js:2:99886)
    at http://localhost:3333/js/prod.main.8ca1f1942537835b0b8c.js:2:51541`)
);
